package io.tim.mvc.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.tim.mvc.form.ActionForm;
import io.tim.mvc.form.FormBuilder;
import io.tim.mvc.util.XmlBean;

/**
 * 针对所有业务处理请求的 Servlet 入口
 * 
 * @author Zhang Nan
 * @since 2017/02/21
 * 
 */
@WebServlet(urlPatterns="/")
public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
     	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
     		
     		// 获得请求的路径，例如 /login 或 /register
     		String servletPath = request.getServletPath();
     		System.out.println("servletpath: " + servletPath);
     		// 根据 web.xml 中配置的属性和 Listener 获取到所有 url 与对应的 ActionForm、Action 的类名信息
     		// 下面需要通过这些类名信息进行反射实例化
     		@SuppressWarnings("unchecked")
			Map<String, XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("mvc-config");
     		XmlBean xmlBean = map.get(servletPath);
     		String formClass = xmlBean.getFormClass();
     		// 得到请求的业务对应的具体的 ActionForm
     		ActionForm form = FormBuilder.build(formClass, request);
     		
     		// 得到请求的业务对应的具体执行业务处理的 Action 类名并做反射实例化
     		String actionClass = xmlBean.getActionClass();
     		Action action = null;
     		String url = "";
     		try {
     			
     			Class<?> cls = Class.forName(actionClass);
     			action = (Action) cls.newInstance();
     			// 调用 action 对应的业务处理类的执行方法，并返回处理后转移的 url
				url = action.execute(request, form, xmlBean.getActionForward());
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("严重错误！控制器异常！");
			}
     		
     		RequestDispatcher dis = request.getRequestDispatcher(url);
     		dis.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}
